<template>
  <div class="auto-review-config">
    <el-tabs v-model="activeTab" class="config-tabs">
      <el-tab-pane label="敏感词管理" name="words">
        <div class="sensitive-words-panel">
          <div class="panel-header">
            <h3>敏感词列表</h3>
            <el-button type="primary" @click="showAddWordDialog">
              <el-icon><Plus /></el-icon>添加敏感词
            </el-button>
          </div>
          
          <div class="search-row">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索敏感词"
              style="width: 250px"
              clearable
              @input="filterSensitiveWords"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-select 
              v-model="filterLevel" 
              placeholder="敏感级别"
              style="width: 120px; margin-left: 10px;"
              clearable
              @change="filterSensitiveWords"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="高" value="high"></el-option>
              <el-option label="中" value="medium"></el-option>
              <el-option label="低" value="low"></el-option>
            </el-select>
          </div>
          
          <el-table
            v-loading="loading.sensitiveWords"
            :data="filteredSensitiveWords"
            style="width: 100%; margin-top: 20px;"
            border
          >
            <el-table-column type="index" width="60" align="center"></el-table-column>
            <el-table-column prop="word" label="敏感词" min-width="150">
              <template #default="scope">
                <span class="sensitive-word">{{ scope.row.word }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="level" label="敏感级别" width="120">
              <template #default="scope">
                <el-tag :type="getSensitiveLevelTag(scope.row.level)">
                  {{ getSensitiveLevelText(scope.row.level) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  plain 
                  @click="deleteSensitiveWord(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="wordCurrentPage"
              v-model:page-size="wordPageSize"
              :page-sizes="[10, 20, 50, 100]"
              background
              layout="total, sizes, prev, pager, next"
              :total="wordTotal"
              @size-change="handleWordSizeChange"
              @current-change="handleWordCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="审核规则配置" name="rules">
        <div class="review-rules-panel">
          <div class="panel-header">
            <h3>自动审核配置</h3>
            <el-button type="primary" @click="showTestDialog">
              <el-icon><Monitor /></el-icon>测试检测功能
            </el-button>
          </div>
          
          <el-form 
            ref="configForm"
            :model="autoReviewConfig" 
            label-width="180px"
            class="config-form"
          >
            <el-divider content-position="left">敏感内容审核</el-divider>
            
            <el-form-item label="启用敏感内容检测">
              <el-switch v-model="autoReviewConfig.enableSensitiveCheck" />
            </el-form-item>
            
            <el-form-item 
              label="敏感内容阈值" 
              :disabled="!autoReviewConfig.enableSensitiveCheck"
            >
              <el-slider 
                v-model="autoReviewConfig.sensitiveThreshold" 
                :disabled="!autoReviewConfig.enableSensitiveCheck" 
                :min="1" 
                :max="10" 
                :step="1" 
                show-stops
              />
              <div class="form-help">
                <el-alert
                  title="数值越低，审核越严格。当检测到的敏感内容超过阈值时，内容将被标记为敏感"
                  type="info"
                  :closable="false"
                  show-icon
                />
              </div>
            </el-form-item>
            
            <el-divider content-position="left">相似度检测</el-divider>
            
            <el-form-item label="启用内容相似度检测">
              <el-switch v-model="autoReviewConfig.enableSimilarityCheck" />
            </el-form-item>
            
            <el-form-item 
              label="内容相似度阈值" 
              :disabled="!autoReviewConfig.enableSimilarityCheck"
            >
              <el-slider 
                v-model="autoReviewConfig.similarityThreshold" 
                :disabled="!autoReviewConfig.enableSimilarityCheck" 
                :min="50" 
                :max="95" 
                :step="5" 
                show-stops
              />
              <div class="form-help">
                <el-alert
                  title="当新内容与已有内容的相似度超过该阈值时，将被标记为重复内容"
                  type="info"
                  :closable="false"
                  show-icon
                />
              </div>
            </el-form-item>
            
            <el-divider content-position="left">垃圾内容过滤</el-divider>
            
            <el-form-item label="启用垃圾内容过滤">
              <el-switch v-model="autoReviewConfig.enableSpamFilter" />
            </el-form-item>
            
            <el-form-item label="过滤规则" :disabled="!autoReviewConfig.enableSpamFilter">
              <el-checkbox-group v-model="autoReviewConfig.spamRules">
                <el-checkbox label="link_limit" border>外链限制</el-checkbox>
                <el-checkbox label="emoji_limit" border>表情符号限制</el-checkbox>
                <el-checkbox label="text_length" border>内容长度检查</el-checkbox>
                <el-checkbox label="keyword_stuffing" border>关键词堆砌检测</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveConfig" :loading="loading.saveConfig">
                保存配置
              </el-button>
              <el-button @click="resetConfig">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 添加敏感词对话框 -->
    <el-dialog
      title="添加敏感词"
      v-model="addWordDialogVisible"
      width="500px"
    >
      <el-form :model="wordForm" label-width="100px" :rules="wordFormRules" ref="wordFormRef">
        <el-form-item label="敏感词" prop="word">
          <el-input v-model="wordForm.word" placeholder="请输入敏感词"></el-input>
        </el-form-item>
        <el-form-item label="敏感级别" prop="level">
          <el-select v-model="wordForm.level" placeholder="请选择敏感级别" style="width: 100%">
            <el-option label="高" value="high"></el-option>
            <el-option label="中" value="medium"></el-option>
            <el-option label="低" value="low"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="wordForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入敏感词描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addWordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddWord" :loading="loading.addWord">
            添加
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 测试对话框 -->
    <SensitiveTestDialog
      v-model:visible="testDialogVisible"
      ref="sensitiveTestDialogRef"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search, Monitor } from '@element-plus/icons-vue';
import { 
  getSensitiveWords, 
  addSensitiveWord, 
  deleteSensitiveWord as apiDeleteSensitiveWord,
  getAutoReviewConfig,
  saveAutoReviewConfig
} from '../../api/admin';
import SensitiveTestDialog from './SensitiveTestDialog.vue';

const props = defineProps({});
const emit = defineEmits([]);

// 标签页
const activeTab = ref('words');

// 敏感词管理相关
const sensitiveWords = ref([]);
const filteredSensitiveWords = ref([]);
const wordTotal = ref(0);
const wordCurrentPage = ref(1);
const wordPageSize = ref(10);
const searchKeyword = ref('');
const filterLevel = ref('');

// 添加敏感词相关
const addWordDialogVisible = ref(false);
const wordForm = ref({
  word: '',
  level: 'medium',
  description: ''
});
const wordFormRef = ref(null);
const wordFormRules = {
  word: [
    { required: true, message: '请输入敏感词', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择敏感级别', trigger: 'change' }
  ]
};

// 自动审核配置
const autoReviewConfig = ref({
  enableSensitiveCheck: true,
  sensitiveThreshold: 3,
  enableSimilarityCheck: true,
  similarityThreshold: 80,
  enableSpamFilter: true,
  spamRules: ['link_limit', 'text_length']
});
const configForm = ref(null);

// 加载状态
const loading = reactive({
  sensitiveWords: false,
  addWord: false,
  saveConfig: false
});

// 敏感级别标签和文本
const getSensitiveLevelTag = (level) => {
  const levels = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info',
    'default': 'info'
  };
  return levels[level] || levels.default;
};

const getSensitiveLevelText = (level) => {
  const texts = {
    'high': '高',
    'medium': '中',
    'low': '低',
    'default': '未知'
  };
  return texts[level] || texts.default;
};

// 加载敏感词列表
const loadSensitiveWords = async () => {
  loading.sensitiveWords = true;
  try {
    const params = {
      current: wordCurrentPage.value,
      size: wordPageSize.value
    };
    
    const response = await getSensitiveWords(params);
    if (response.code === 200) {
      sensitiveWords.value = response.data.records || [];
      wordTotal.value = response.data.total || 0;
      filterSensitiveWords();
      
      // 如果返回数据为空且当前页不是第一页，返回到第一页
      if (sensitiveWords.value.length === 0 && wordCurrentPage.value > 1) {
        wordCurrentPage.value = 1;
        await loadSensitiveWords();
      }
    } else {
      ElMessage.error(response.message || '获取敏感词列表失败');
    }
  } catch (error) {
    console.error('获取敏感词列表失败:', error);
    ElMessage.error('获取敏感词列表失败: ' + (error.message || '未知错误'));
    sensitiveWords.value = [];
    wordTotal.value = 0;
  } finally {
    loading.sensitiveWords = false;
  }
};

// 过滤敏感词
const filterSensitiveWords = () => {
  if (!searchKeyword.value && !filterLevel.value) {
    filteredSensitiveWords.value = [...sensitiveWords.value];
    return;
  }
  
  filteredSensitiveWords.value = sensitiveWords.value.filter(item => {
    const matchKeyword = !searchKeyword.value || 
      item.word.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (item.description && item.description.toLowerCase().includes(searchKeyword.value.toLowerCase()));
    
    const matchLevel = !filterLevel.value || item.level === filterLevel.value;
    
    return matchKeyword && matchLevel;
  });
};

// 处理敏感词分页
const handleWordSizeChange = (val) => {
  wordPageSize.value = val;
  loadSensitiveWords();
};

const handleWordCurrentChange = (val) => {
  wordCurrentPage.value = val;
  loadSensitiveWords();
};

// 显示添加敏感词对话框
const showAddWordDialog = () => {
  wordForm.value = {
    word: '',
    level: 'medium',
    description: ''
  };
  addWordDialogVisible.value = true;
  nextTick(() => {
    if (wordFormRef.value) {
      wordFormRef.value.resetFields();
    }
  });
};

// 提交添加敏感词
const submitAddWord = async () => {
  if (!wordFormRef.value) return;
  
  await wordFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.addWord = true;
    try {
      const response = await addSensitiveWord(wordForm.value);
      if (response.code === 200) {
        ElMessage.success('添加敏感词成功');
        addWordDialogVisible.value = false;
        loadSensitiveWords();
      } else {
        ElMessage.error(response.message || '添加敏感词失败');
      }
    } catch (error) {
      console.error('添加敏感词失败:', error);
      ElMessage.error('添加敏感词失败');
    } finally {
      loading.addWord = false;
    }
  });
};

// 删除敏感词
const deleteSensitiveWord = async (word) => {
  try {
    await ElMessageBox.confirm(`确定要删除敏感词"${word.word}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await apiDeleteSensitiveWord(word.id);
    if (response.code === 200) {
      ElMessage.success('删除成功');
      loadSensitiveWords();
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除敏感词失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 加载自动审核配置
const loadAutoReviewConfig = async () => {
  try {
    const response = await getAutoReviewConfig();
    if (response.code === 200) {
      autoReviewConfig.value = {
        ...autoReviewConfig.value,
        ...response.data
      };
    } else {
      ElMessage.error(response.message || '获取自动审核配置失败');
    }
  } catch (error) {
    console.error('获取自动审核配置失败:', error);
    ElMessage.error('获取自动审核配置失败');
  }
};

// 保存自动审核配置
const saveConfig = async () => {
  loading.saveConfig = true;
  try {
    // 确保配置数据合法
    if (autoReviewConfig.value.enableSensitiveCheck && 
        (autoReviewConfig.value.sensitiveThreshold < 1 || autoReviewConfig.value.sensitiveThreshold > 10)) {
      ElMessage.warning('敏感内容阈值必须在1-10之间');
      return;
    }
    
    if (autoReviewConfig.value.enableSimilarityCheck && 
        (autoReviewConfig.value.similarityThreshold < 50 || autoReviewConfig.value.similarityThreshold > 95)) {
      ElMessage.warning('内容相似度阈值必须在50-95之间');
      return;
    }
    
    const response = await saveAutoReviewConfig(autoReviewConfig.value);
    if (response.code === 200) {
      ElMessage.success('保存配置成功');
      
      // 保存成功后重新加载配置以确认更新
      await loadAutoReviewConfig();
    } else {
      ElMessage.error(response.message || '保存配置失败');
    }
  } catch (error) {
    console.error('保存配置失败:', error);
    ElMessage.error('保存配置失败: ' + (error.message || '未知错误'));
  } finally {
    loading.saveConfig = false;
  }
};

// 重置配置
const resetConfig = async () => {
  try {
    await ElMessageBox.confirm('确定要重置配置吗？这将恢复为最后保存的设置', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loadAutoReviewConfig();
  } catch (error) {
    // 用户取消，不做处理
  }
};

// 测试对话框
const testDialogVisible = ref(false);
const sensitiveTestDialogRef = ref(null);

// 显示测试对话框
const showTestDialog = () => {
  testDialogVisible.value = true;
};

// 初始化
onMounted(() => {
  loadSensitiveWords();
  loadAutoReviewConfig();
});

// 暴露方法给父组件
defineExpose({
  loadSensitiveWords,
  loadAutoReviewConfig
});
</script>

<style scoped>
.auto-review-config {
  width: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.sensitive-word {
  color: #F56C6C;
  font-weight: bold;
}

.config-form {
  max-width: 800px;
  margin: 0 auto;
}

.config-form h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 18px;
  color: #303133;
  text-align: center;
}

.form-help {
  margin-top: 10px;
}

:deep(.el-checkbox.is-bordered) {
  margin-right: 10px;
  margin-bottom: 10px;
}

:deep(.el-alert) {
  padding: 8px 16px;
}

:deep(.el-alert__title) {
  font-size: 12px;
}

@media (max-width: 768px) {
  .search-row {
    flex-direction: column;
  }
  
  .search-row .el-input,
  .search-row .el-select {
    width: 100% !important;
    margin-left: 0 !important;
  }
  
  .config-form {
    padding: 0 10px;
  }
}
</style> 